package com.ruoyi.web.es.controller;

import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.annotation.Anonymous;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.WrapperQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.Map;

@Anonymous
@RestController
public class LogstachController {

    @Autowired
    private RestHighLevelClient rstHighLevelClient;


    @PostMapping("/query2")
    public SearchResponse userEsClient() throws IOException {

        String index_name = "aqyy_log2024081*";


        String json = "{\"query\": {\"match\": {\"title\": \"hello world\"}}}";
        //language=JSON5
        String dsl = "{\n" +
                "  \"match_all\": {}\n" +
                "}";


        WrapperQueryBuilder queryBuilder = new WrapperQueryBuilder(dsl);

        SearchRequest searchRequest = new SearchRequest();
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        // 设置分页
        searchSourceBuilder.query(queryBuilder).from((int) 0).size((int) 10000);
        searchRequest.source(searchSourceBuilder).indices(index_name);
        SearchResponse searchResp = rstHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
        // 计算返回的条数
        SearchHit[] searchHits = searchResp.getInternalResponse().hits().getHits();
        for (SearchHit ss: searchHits) {
            Map<String, Object> sourceAsMap = ss.getSourceAsMap();
            String id = (String) sourceAsMap.get("id");
            String logTime = (String) sourceAsMap.get("logTime");
            String serviceName = (String) sourceAsMap.get("serviceName");
            String jobNumber = (String) sourceAsMap.get("jobNumber");
            String userName = (String) sourceAsMap.get("userName");

            System.out.println("=================================");

            System.out.println(id);
            System.out.println(logTime);
            System.out.println(serviceName);
            System.out.println(jobNumber);
            System.out.println(userName);
        }

        return searchResp;
    }


    @GetMapping("/LogstachTest")
    public String LogstachTest(){
        return "haode";
    }

    @PostMapping("/LogstachTestmes")
    public void LogstachTestmes(@RequestBody Map<String,String> map){

        String value = map.get("message");
        System.out.println(value);
    }

}
